import 'package:flutter/cupertino.dart';
import 'package:acgn_pioneer/event/model_event.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import '../public.dart';

/// 首页
class HomePage extends StatefulWidget {
  HomePage({Key key}) : super(key: key);

  @override
  HomePageState createState() {
    return new HomePageState();
  }
}

class HomePageState extends State<HomePage> {
  HomeProvider model;
  UserProvider user;
  var flag = true;

  @override
  void initState() {
    /// 测试全局事件
    ACGN.event.fire('进入首页');
    ACGN.event.fire(new HttpErrorEvent(-1, 'xxxxx'));

    /// 测试 shared_preferences
    SpUtil.putInt('keyInt', 1);
    LogUtil.v(SpUtil.getInt('keyInt'));

    WidgetsBinding.instance.addPostFrameCallback((_) {
      model.changeName('xxxxx');
      // model = Provider.of<HomeProvider>(context, listen: false).xxxx();
      // setState(() {});
    });

    super.initState();
  }

  List<String> items = ["1", "2", "3", "4", "5", "6", "7", "8"];
  RefreshController _refreshController =
      RefreshController(initialRefresh: false);

  void _onRefresh() async {
    // monitor network fetch
    await Future.delayed(Duration(milliseconds: 1000));
    // if failed,use refreshFailed()
    _refreshController.refreshCompleted();
  }

  void _onLoading() async {
    // monitor network fetch
    await Future.delayed(Duration(milliseconds: 1000));
    // if failed,use loadFailed(),if no data return,use LoadNodata()
    items.add((items.length + 1).toString());
    if (mounted) setState(() {});
    _refreshController.loadComplete();
  }

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Container(
        height: 100,
        width: 100,
        color: Colors.red,
        child: Text('xxx'),
      ),
    );
    // throw Error();
    // Future.delayed(Duration(seconds: 1)).then((e) => Future.error("xxx"));

    /// 测试provider
    // model = Provider.of<HomeProvider>(context);
    // user = Provider.of<UserProvider>(context);
    // var theme = Provider.of<ThemeProvider>(context);
    // var local = Provider.of<LocalProvider>(context);
    model = Provider.of<HomeProvider>(context);
    if (model == null) {
      return Container();
    }
    if (model.homeModel == null) {
      model.homeModel = HomeModel.fromJson({'name': '首页'});
      LogUtil.v(model.homeModel.toJson());
    }
    return Scaffold(
        backgroundColor: Colors.white,
        body: Stack(
          alignment: Alignment.center,
          children: <Widget>[
            Center(
                child: Text(
              model.homeModel.name,
              // I18n.of(context).Title,
              style: TextStyle(fontSize: Rem(60)),
            )),
            Positioned(
              bottom: Rem(20),
              child: new OutlineButton(
                onPressed: () {
                  ACGN.toast.loading();
                  // PopUtil.showSlidePop(
                  //     context: context,
                  //     child: Container(
                  //         height: ScreenUtil.getInstance().screenHeight,
                  //         child: ReaderPageMain(
                  //           isPopNested: true,
                  //           comicId: 5323,
                  //         )),
                  //     barrierColor: Colors.white.withOpacity(0.7));

                  return;
                  // theme.switchFont(flag ? 1 : 0);
                  // local.switchLocale(flag ? 1 : 0);
                  // theme.switchTheme(color: Colors.primaries[9]);
                  model.changeName('新首页名称');

                  HomeService().getHomeData();
                  flag = !flag;
                },
                child: new Padding(
                  padding: EdgeInsets.all(Rem(4)),
                  child: new Text(
                    '改变主题 + 文字 + 语言',
                    textAlign: TextAlign.center,
                    style: TextStyle(fontSize: Rem(32)),
                  ),
                ),
              ),
            ),
            Positioned(
              top: 0,
              child: Container(
                decoration: BoxDecoration(color: Colors.red),
                height: 300,
                width: 300,
                child: SmartRefresher(
                  enablePullDown: true,
                  enablePullUp: true,
                  header: WaterDropHeader(),
                  footer: CustomFooter(
                    builder: (BuildContext context, LoadStatus mode) {
                      Widget body;
                      if (mode == LoadStatus.idle) {
                        body = Text("pull up load");
                      } else if (mode == LoadStatus.loading) {
                        body = CupertinoActivityIndicator();
                      } else if (mode == LoadStatus.failed) {
                        body = Text("Load Failed!Click retry!");
                      } else if (mode == LoadStatus.canLoading) {
                        body = Text("release to load more");
                      } else {
                        body = Text("No more Data");
                      }
                      return Container(
                        height: 55.0,
                        child: Center(child: body),
                      );
                    },
                  ),
                  controller: _refreshController,
                  onRefresh: _onRefresh,
                  onLoading: _onLoading,
                  child: ListView.builder(
                    itemBuilder: (c, i) =>
                        Card(child: Center(child: Text(items[i]))),
                    itemExtent: 100.0,
                    itemCount: items.length,
                  ),
                ),
              ),
            )
          ],
        ));
  }
}
